package com.jixiang.tracedata.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.*;

/**
 * @author quanbiao
 * @date 2018-09-10
 * 线程池定义
 */
@Configuration
public class ThreadPoolConfig {

    /**
     * ThreadPoolTaskExecutor
     * @return 接收
     */
    @Bean
    public ExecutorService asyncJmsReceive(){
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                5,
                20,
                10000L,
                TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>());
        threadPoolExecutor.allowCoreThreadTimeOut(false);
        threadPoolExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        return threadPoolExecutor;
    }

    @Bean
    public Executor asyncDataBaseTask() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(20);
        executor.setMaxPoolSize(100);
        executor.setQueueCapacity(20);
        executor.setThreadNamePrefix("asyncDataBaseTask-");

        // rejection-policy：当pool已经达到max size的时候，如何处理新任务
        // CALLER_RUNS：不在新线程中执行任务，而是有调用者所在的线程来执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }
}
